package net.pingfang.devicelock.core;

import lombok.extern.slf4j.Slf4j;
import net.pingfang.devicelock.util.DeviceDecodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;


@Component
@Slf4j
@EnableIntegration
public class DeviceGpsService {


    private final MessageChannel outboundChannel;

    private final ThreadPoolTaskExecutor taskExecutor;

    private final ThreadLocal<SimpleDateFormat> threadLocalSdf =
            ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMddHHmmss"));



    @Autowired  // 当有多个同名Bean时需显式指定
    public DeviceGpsService(@Qualifier("outboundChannel") MessageChannel outboundChannel,
                            @Qualifier("tcpTaskExecutor") ThreadPoolTaskExecutor taskExecutor
                          ) {
        this.outboundChannel = outboundChannel;
        this.taskExecutor = taskExecutor;
    }

    /**
     * 对于某一个电子锁，收到上传信息的一刻证明电子锁在线，是否用线程监听电子锁下一次传输信息，若未收到是否判定为离线？
     * 对于接收到payload字节码使用多线程管理
     */
//    @Async("tcpTaskExecutor")
//    @ServiceActivator(inputChannel = "tcpInputChannel")
//    public void handleMessage(byte[] bys) {
//
//            // 自定义业务逻辑（如解析 JSON、持久化数据等）将数据通过websocket上传到vue
//            ObjectMapper objectMapper = new ObjectMapper();
//            try {
//                objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
//                // JSON → 实体类（自动映射嵌套结构）
//                Code0200 entity = objectMapper.readValue(DeviceDecodeUtil.GPSDecode(
//                        new String(bys, StandardCharsets.UTF_8)), Code0200.class);
//                //发送信息到前端vue
//                CustomWebSocketHandler customWebSocketHandler = new CustomWebSocketHandler(taskExecutor);
//                customWebSocketHandler.sendToAll(entity.toString());
//                log.info("entity{}", entity);
//            } catch (JsonProcessingException e) {
//                log.error("运行时异常:"+e.getMessage());
//            }
//
//    }


    //转16进制
    public static byte[] hexStrToByteArray(String hexStr) {
        hexStr = hexStr.replaceAll(" ", "");
        byte[] bytes = new byte[hexStr.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            String sub = hexStr.substring(2 * i, 2 * i + 2);
            bytes[i] = (byte) Integer.parseInt(sub, 16);
        }
        return bytes;
    }


    //向设备发送施封 解封信息
    public void Send_Seal(String Code,short seal){
        Message<byte[]> msg = MessageBuilder.withPayload(
                hexStrToByteArray(DeviceDecodeUtil.Lock_Device(Code,seal))).build();
        log.info("发送指令信息:{}--->", Arrays.toString(msg.getPayload()));

        outboundChannel.send(msg);
    }


    //向阅读器发送施封信息
    public void Send_SealLock(String LockName,String passWord){
        taskExecutor.execute(()->{
            String formattedTime = threadLocalSdf.get().format(new Date());
            Message<byte[]> msg = MessageBuilder.withPayload(
                    DeviceDecodeUtil.LockCmd(LockName,passWord,formattedTime)).build();
            log.info("发送指令信息1:{}--->",Arrays.toString(msg.getPayload()));
//            hhd_boundChannel.send(msg);
        });

    }




    // 6. 使用示例
    public void NettyConnect(String LockName,String passWord) {
        taskExecutor.execute(()->{

        });

    }

    //向设备发送查询参数信息
//    public void Send_Params(String code){
//
//    }

    /**
     * 没有收到信号时的处理、施解封后未收到回传数据的状态处理
     *
     * 1.主动向设备发送信息
     */
    //设备在线 离线状态判定
    public boolean is_alive(){
        return false;
    }



}
